/*
 * @Author       : lptecodad lptecodad@sina.com
 * @Date         : 2023-04-21 01:49:03
 * @LastEditors  : lptecodad lptecodad@sina.com
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
import * as XLSX from 'xlsx';
// 图像转base64
export const fileToBase64 = (file: Blob) => {
	return new Promise((resolve, reject) => {
		let reader = new FileReader();
		let result = '';
		reader.readAsDataURL(file);
		reader.onload = () => {
			result = reader.result as string;
			result = result.replace(/^data:image\/\w+;base64,/, '');
		};
		reader.onerror = (err) => {
			reject(err);
		};
		reader.onloadend = () => {
			resolve(result);
		};
	});
};

export const readFile = (file: Blob) => {
	return new Promise((resolve) => {
		let reader = new FileReader();
		reader.readAsBinaryString(file);
		reader.onload = (e) => {
			resolve(e.target?.result);
		};
	});
};

export const readXlsxFile = async (file: File) => {
	let data = await readFile(file);
	let workbook = XLSX.read(data, { type: 'binary' });
	let worksheet = workbook.Sheets[workbook.SheetNames[0]];
	data = XLSX.utils.sheet_to_json(worksheet);
	return data;
};
export const exportExcel = (fileName: string, content: { header: any[]; columns: any[][]; footer: any[] }) => {
	// 生命变量
	let tableData = [] as any[][];

	// 填充header
	tableData.push(content.header);

	// 遍历columns
	content.columns?.forEach((val) => {
		tableData.push(val);
	});

	// 填充footer
	tableData.push(content.footer);

	// 写入文档
	let workSheet = XLSX.utils.aoa_to_sheet(tableData);
	let bookNew = XLSX.utils.book_new();
	XLSX.utils.book_append_sheet(bookNew, workSheet, 'Sheet1'); // 工作簿名称

	XLSX.writeFile(bookNew, fileName + '.xlsx'); // 保存的文件名
};

// export const exportExcel = (fileName: string, props: any, dataList: any[]) => {
//     let tableData = [] as any[]
//     let rowHeader = [] as string[]
//     for (let idx in props) {
//         rowHeader.push(props[idx])
//     }
//     tableData.push(rowHeader)
//     dataList.forEach(item => {
//         let row = [] as string[]
//         for (let idx in props) {
//             row.push(item[idx])
//         }
//         tableData.push(row)
//     })
//     let workSheet = XLSX.utils.aoa_to_sheet(tableData);
//     let bookNew = XLSX.utils.book_new();
//     XLSX.utils.book_append_sheet(bookNew, workSheet, 'Sheet1') // 工作簿名称

//     XLSX.writeFile(bookNew, fileName + '.xlsx') // 保存的文件名

// }
